class ProjectController < StatController
  before_filter :login_required

  def search
    if !session[:secret_search]
      session[:secret_search] = Array.new
    end
    p = Project.find(:first, :conditions=>["gencode=?", params[:search]])
    if p
      session[:secret_search] = session[:secret_search] << "#{p.id}"
      redirect_to :action=>"select_project", :id=>params[:search]
    else
      redirect_to :action=>"list"
    end
  end

  def do_save_as
    master_project = Project.find(session[:selected_project_id])
    copy_project = Project.new
    copy_project.name = params[:name]
    copy_project.gencode = random_string(16)
    copy_project.user_id = session[:user].id
    if master_project.user_id==session[:user].id
      copy_project.parent_id = master_project.parent_id
    end
    shared_word = ''
    if master_project.shared
      shared_word += "#{master_project.shared}<br/>"
    end
    begin
      mo = User.find(master_project.user_id)
      shared_word += "#{mo.title}#{mo.firstname} #{mo.lastname} at #{Time.now}"
    rescue
    end
    if !shared_word.empty?
      copy_project.shared = shared_word
    end
    copy_project.save
    copy_project.weight = copy_project.id
    copy_project.save
    project_setting = ProjectSetting.new
    project_setting.project_id = copy_project.id
    project_setting.save
    if params[:chk_general]=='y'
      copy_general(master_project, copy_project)
    end
    if params[:chk_data]=='y'
      copy_data(master_project, copy_project)
    end
    if params[:chk_result]=='y'
      copy_result(master_project, copy_project)
    end
    if params[:chk_paper]=='y'
      copy_paper(master_project, copy_project)
    end
    session[:selected_project_id] = copy_project.id
    redirect_to :action=>"general_page", :word=>"Saved : #{Time.now}"
  end

  def copy_general(master_project, copy_project)
    begin
      copy_project.keyword = master_project.keyword
      copy_project.description = master_project.description
      copy_project.save
    rescue
    end
  end

  def copy_data(master_project, copy_project)
    begin
      m_project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", master_project.id])
      c_project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", copy_project.id])
      c_project_setting.update_attributes(m_project_setting.attributes)
      c_project_setting.project_id = copy_project.id
      c_project_setting.save

      m_running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=?", m_project_setting.id], :order=>"id")
      m_running_stocks.each do |s|
        c_running_stock = RunningStock.new(s.attributes)
        c_running_stock.project_setting_id = c_project_setting.id
        c_running_stock.save
      end
    rescue
    end
  end

  def copy_result(master_project, copy_project)
    begin
      m_running_results = RunningResult.find(:all, :conditions=>["project_id=?", master_project.id], :order=>"id")
      m_running_results.each do |r|
        c_running_result = RunningResult.new(r.attributes)
        c_running_result.project_id = copy_project.id
        copy_project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?",copy_project.id])
        c_running_result.project_setting_id = copy_project_setting.id
        c_running_result.user_id = session[:user].id
        c_running_result.save
      end
    rescue
    end
  end

  def copy_paper(master_project, copy_project)
    begin
      m_papers = Attachment.find(:all, :conditions=>["project_id=?", master_project.id], :order=>"id")
      m_papers.each do |p|
        c_paper = Attachment.new(p.attributes)
        c_paper.user_id = session[:user].id
        c_paper.project_id = copy_project.id
        c_paper.gencode = random_string(16)
        c_paper.save
        c_paper.weight = c_paper.id
        c_paper.save
        FileUtils.copy_file("#{RAILS_ROOT}/public/files/#{p.id}","#{RAILS_ROOT}/public/files/#{c_paper.id}")
      end
    rescue
    end
  end

  def delete_paper
    attachment = Attachment.find(:first, :conditions=>["gencode=?", params[:id]])
    if attachment
      attachment.destroy
    end
    redirect_to :action=>"paper_page", :word=>"Deleted : #{Time.now}"
  end

  def upload_paper
    if params['attachment']['url'].empty?
      if params['attachment']['tmp_file']
        filename = params['attachment']['tmp_file'].original_filename # This makes sure filenames are sane
        content = params['attachment']['tmp_file'].read
        content_type = params['attachment']['tmp_file'].content_type
        params['attachment']['filename'] = filename
        params['attachment'].delete('tmp_file') # let's remove the field from the hash, because there's no such field in the DB anyway.
        attachment = Attachment.new(params['attachment'])
        attachment.content_type = content_type
        attachment.project_id = session[:selected_project_id]
        attachment.user_id = session[:user].id
        attachment.a_type = "I"
        attachment.gencode = random_string(16)
        attachment.save
        attachment.weight = attachment.id
        attachment.save
        path = "#{RAILS_ROOT}/public/files/#{attachment.id}"
        File.open(path,"wb") { |f|
          f << content
        }
      end
    else
        attachment = Attachment.new
        attachment.url = params['attachment']['url']
        attachment.name = params['attachment']['name']
        attachment.project_id = session[:selected_project_id]
        attachment.user_id = session[:user].id
        attachment.a_type = "E"
        attachment.gencode = random_string(16)
        attachment.save
        attachment.weight = attachment.id
        attachment.save
    end
    redirect_to :action=>"paper_page", :word=>"Saved : #{Time.now}"
  end

  def gen_blank
    project = Project.new
    project.name = 'Preparing Project'
    project.user_id = session[:user_id]
    project.gencode = random_string(16)
    project.save
    project.weight = project.id
    project.save

    project_setting = ProjectSetting.new
    project_setting.project_id = project.id
    project_setting.save

    session[:selected_project_id] = project.id
    redirect_to :action=>"general_page"
  end
  
  def list
    session[:selected_project_id] = nil
    @all_projects = all_active_project_array
    #@projects = Project.find(:all, :conditions=>["user_id=? AND project_status=?", session[:user_id], 'Active'], :order=>"name")
    @tab = "list"
    render :action=>"list", :layout=>"blank_layout"
  end

  def select_project
    p = Project.find(:first, :conditions=>["gencode=?", params[:id]], :order=>"id")
    if p
      session[:selected_project_id] = p.id
      redirect_to :action=>"general_page"
    else
      session[:selected_project_id] = nil
      redirect_to :action=>"list"
    end
  end

  def save_as
    @word = nil
    if params[:word]
      @word = params[:word]
    end
    @project = Project.find(session[:selected_project_id])
    @all_projects = all_active_project_array
    render :action=>"save_as", :layout=>"blank_layout"
  end

  def general_page
    @word = nil
    if params[:word]
      @word = params[:word]
    end
    @tab = "general"
    @project = Project.find(session[:selected_project_id])
    @all_projects = all_active_project_array
    #@projects = Project.find(:all, :conditions=>["user_id=? AND project_status=?", session[:user_id], 'Active'], :order=>"name")
    render :action=>"general_page", :layout=>"blank_layout"
  end

  def all_active_project_array
    project_array = Array.new
    main_projects = Project.find(:all, :conditions=>["user_id=? AND project_status=? AND parent_id is null", session[:user_id], 'Active'], :order=>"name")
    main_projects.each do |p|
      project_array = project_array << "#{p.id}"
      project_array = project_array << all_active_subproject_array(p.id, "#{p.id}|")
    end
    return project_array.flatten
  end

  def all_active_subproject_array(parent_id, prefix)
    project_array = Array.new
    projects = Project.find(:all, :conditions=>["user_id=? AND project_status=? AND parent_id=?", session[:user_id], 'Active', parent_id], :order=>"name")
    projects.each do |p|
      project_array = project_array << "#{prefix}#{p.id}"
      project_array = project_array << all_active_subproject_array(p.id, "#{prefix}#{p.id}|")
    end
    return project_array.flatten
  end

  def general_page_save
    project = Project.find(session[:selected_project_id])
    if params[:parent_id].to_s=="0"
      project.parent_id = nil
    else
      project.parent_id = params[:parent_id]
    end
    project.name = params[:name]
    project.description = params[:description]
    project.keyword = params[:keyword]
    project.save
    redirect_to :action=>"general_page", :word=>"Saved : #{Time.now}"
  end

  def paper_page
    @word = nil
    if params[:word]
      @word = params[:word]
    end
    @tab = "paper"
    @project = Project.find(session[:selected_project_id])
    @all_projects = all_active_project_array
    @papers = Attachment.find(:all, :conditions=>["project_id=?", session[:selected_project_id]], :order=>"id")
    #@projects = Project.find(:all, :conditions=>["user_id=? AND project_status=?", session[:user_id], 'Active'], :order=>"name")
    render :action=>"paper_page", :layout=>"blank_layout"
  end

  def data_page
    @word = nil
    if params[:word]
      @word = params[:word]
    end
    @tab = "data"
    @project = Project.find(session[:selected_project_id])
    @project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", session[:selected_project_id]])
    @all_projects = all_active_project_array
    @running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=?",@project_setting.id], :order=>"id")
    #@projects = Project.find(:all, :conditions=>["user_id=? AND project_status=?", session[:user_id], 'Active'], :order=>"name")
    render :action=>"data_page", :layout=>"blank_layout"
  end

  def data_page_save
    min_est = params[:setting][:min_est]
    max_est = params[:setting][:max_est]
    min_event = params[:setting][:min_event]
    max_event = params[:setting][:max_event]
    leadlag_size = '0'
    begin
      if !params[:setting][:leadlag_size].empty?
        leadlag_size = params[:setting][:leadlag_size]
        min_event = "#{params[:setting][:min_event].to_i-params[:setting][:leadlag_size].to_i}"
        max_event = "#{params[:setting][:max_event].to_i+params[:setting][:leadlag_size].to_i}"
      end
    rescue
    end

    project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", session[:selected_project_id]])
    if check_window(min_est, max_est, min_event, max_event, leadlag_size)
      project_setting.update_attributes(params[:setting])
    end
    project_setting.total_stock = 0
    project_setting.rm_type = 'S'
    project_setting.rm_id = 1
    project_setting.save


    running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=?", project_setting])
    running_stocks.each do |rs|
      rs.destroy
    end

    for i in 1..params[:total_item].to_i do
      if params["data_#{i}"]
        if params["date_#{i}"]
#          add_running_stock(params["data_#{i}"], params["date_#{i}"], params["stock_type_#{i}"], params["check_#{i}"], project_setting.id, min_est, max_est, min_event, max_event)
          add_running_stock2(params["data_#{i}"], params["date_#{i}"], params["stock_type_#{i}"], params["check_#{i}"], params["est_de_#{i}"], params["event_de_#{i}"], project_setting.id, min_est, max_est, min_event, max_event)
        end
      end
    end

    market_type = "S"
    market_id = 1
    as_market = RunningStock.find(:first, :conditions=>["project_setting_id=? AND rm_flag=?", project_setting,'Y'])
    if as_market
      market_type = as_market.stock_type
      if as_market.stock_type=='S'
        market_id = as_market.stock_id
      else
        market_id = as_market.user.stock_id
      end
    end
    running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND rm_flag!=?", project_setting,'Y'])
    running_stocks.each do |rs|
      fill_market_window_date(rs.id, market_id, market_type, min_est, max_est, min_event, max_event)
    end

    redirect_to :action=>"data_page", :word=>"Saved : #{Time.now}"
  end

  def check_event_date(id, event_date, stock_type)
    st = nil
    if stock_type=='S'
      stock = Stock.find(:first, :conditions=>["id=?",id])
      if stock
        st = StockTrade.find(:first, :conditions=>["stock_id=? AND trade_date=? AND daily_return IS NOT NULL",stock.id,event_date], :order=>"id")
      end
    else
      stock = UserStock.find(:first, :conditions=>["id=?",id])
      if stock
        st = UserStockTrade.find(:first, :conditions=>["user_stock_id=? AND trade_date=? AND daily_return IS NOT NULL",stock.id,event_date], :order=>"id")
      end
    end
    if st
      return true
    else
      return false
    end
  end

  def check_window(min_est, max_est, min_event_v, max_event_v, leadlag_size)
    min_event = "#{min_event_v.to_i+leadlag_size.to_i}"
    max_event = "#{max_event_v.to_i-leadlag_size.to_i}"
    error_count = 0
    begin
      if min_est.empty?
        error_count += 1
      end
      if max_est.empty?
        error_count += 1
      end
      if min_event.empty?
        error_count += 1
      end
      if max_event.empty?
        error_count += 1
      end
      if min_est.to_i>0 || max_est.to_i>0
        error_count += 1
      end
      if min_est.to_i > max_est.to_i
        error_count += 1
      end
      if min_event.to_i>0 || max_event.to_i<0
        error_count += 1
      end
      if max_est.to_i+1 != min_event.to_i
        error_count += 1
      end
    rescue
      error_count += 1
    end
    if error_count==0
      return true
    else
      return false
    end
  end

  def add_running_stock(id, event_date, stock_type, as_market, project_setting_id, min_est, max_est, min_event, max_event)
    if event_date.empty? && as_market==nil
      
    elsif !check_event_date(id, event_date, stock_type)
      
    else
      running_stock = RunningStock.new
      running_stock.project_setting_id = project_setting_id
      running_stock.stock_type = stock_type
      if stock_type=="S"
        running_stock.stock_id = id
      else
        running_stock.user_stock_id = id
      end
      if as_market
        running_stock.rm_flag = 'Y'
      end
      if !event_date.empty?
        running_stock.event_date = Date.parse(event_date)
        pass,date = check_est_event_pass(id, stock_type, event_date, min_est, max_est, min_event, max_event)
        running_stock.min_est_date = date[0]
        running_stock.max_est_date = date[1]
        running_stock.min_event_date = date[2]
        running_stock.max_event_date = date[3]
        running_stock.min_est_pass = pass[0]
        running_stock.max_est_pass = pass[1]
        running_stock.min_event_pass = pass[2]
        running_stock.max_event_pass = pass[3]
      end
      running_stock.save
      if as_market
        running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND id!=?",project_setting_id, running_stock.id], :order=>"id")
        running_stocks.each do |rs|
          rs.rm_flag = 'N'
          rs.save
        end
        ps = ProjectSetting.find(project_setting_id)
        ps.rm_id = id
        ps.rm_type = stock_type
        ps.save
      end
      total = RunningStock.count(:conditions=>["project_setting_id=? AND rm_flag!=?", project_setting_id, 'Y'])
      ps = ProjectSetting.find(project_setting_id)
      ps.total_stock = total
      ps.save
    end
  end

  def add_running_stock2(id, event_date, stock_type, as_market, est_de, event_de, project_setting_id, min_est, max_est, min_event, max_event)
    if event_date.empty? && as_market==nil

    elsif !check_event_date(id, event_date, stock_type)

    else
      running_stock = nil
      if stock_type=="S"
        if as_market
          running_stock = RunningStock.find(:first, :conditions=>["project_setting_id=? AND stock_type=? AND stock_id=? AND rm_flag=? AND event_date=?", project_setting_id, stock_type, id, 'Y', event_date])
        else
          running_stock = RunningStock.find(:first, :conditions=>["project_setting_id=? AND stock_type=? AND stock_id=? AND rm_flag=? AND event_date=?", project_setting_id, stock_type, id, 'N', event_date])
        end
      else
        if as_market
          running_stock = RunningStock.find(:first, :conditions=>["project_setting_id=? AND stock_type=? AND user_stock_id=? AND rm_flag=? AND event_date=?", project_setting_id, stock_type, id, 'Y', event_date])
        else
          running_stock = RunningStock.find(:first, :conditions=>["project_setting_id=? AND stock_type=? AND user_stock_id=? AND rm_flag=? AND event_date=?", project_setting_id, stock_type, id, 'N', event_date])
        end
      end
      if !running_stock
        running_stock = RunningStock.new
      end
      running_stock.project_setting_id = project_setting_id
      running_stock.stock_type = stock_type
      if stock_type=="S"
        running_stock.stock_id = id
      else
        running_stock.user_stock_id = id
      end
      if as_market
        running_stock.rm_flag = 'Y'
      else
        running_stock.rm_flag = 'N'
      end
      if !event_date.empty?
        running_stock.event_date = Date.parse(event_date)
        pass,date = check_est_event_pass(id, stock_type, event_date, min_est, max_est, min_event, max_event)
        running_stock.min_est_date = date[0]
        running_stock.max_est_date = date[1]
        running_stock.min_event_date = date[2]
        running_stock.max_event_date = date[3]
        running_stock.min_est_pass = pass[0]
        running_stock.max_est_pass = pass[1]
        running_stock.min_event_pass = pass[2]
        running_stock.max_event_pass = pass[3]
      end
      if est_de.empty?
        running_stock.est_de = nil
      else
        running_stock.est_de = est_de.to_f
      end
      if event_de.empty?
        running_stock.event_de = nil
      else
        running_stock.event_de = event_de.to_f
      end
      running_stock.save
      if as_market
        running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND id!=?",project_setting_id, running_stock.id], :order=>"id")
        running_stocks.each do |rs|
          rs.rm_flag = 'N'
          rs.save
        end
        ps = ProjectSetting.find(project_setting_id)
        ps.rm_id = id
        ps.rm_type = stock_type
        ps.save
      end
      total = RunningStock.count(:conditions=>["project_setting_id=? AND rm_flag!=?", project_setting_id, 'Y'])
      ps = ProjectSetting.find(project_setting_id)
      ps.total_stock = total
      ps.save
    end
  end

  def update_running_stock(running_stock, min_est, max_est, min_event, max_event)
      id = nil
      if running_stock.stock_type=='S'
        id = running_stock.stock_id
      else
        id = running_stock.user_stock_id
      end
      pass,date = check_est_event_pass(id, running_stock.stock_type, running_stock.event_date, min_est, max_est, min_event, max_event)
      running_stock.min_est_date = date[0]
      running_stock.max_est_date = date[1]
      running_stock.min_event_date = date[2]
      running_stock.max_event_date = date[3]
      running_stock.min_est_pass = pass[0]
      running_stock.max_est_pass = pass[1]
      running_stock.min_event_pass = pass[2]
      running_stock.max_event_pass = pass[3]
      running_stock.save
  end

  def model_page
    @word = nil
    if params[:word]
      @word = params[:word]
    end
    @tab = "model"
    @project = Project.find(session[:selected_project_id])
    @project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", session[:selected_project_id]])
    @all_projects = all_active_project_array
    #@projects = Project.find(:all, :conditions=>["user_id=? AND project_status=?", session[:user_id], 'Active'], :order=>"name")
    render :action=>"model_page", :layout=>"blank_layout"
  end

  def model_page_save
    project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", session[:selected_project_id]])
    if params[:mm_flag]
      project_setting.mm_flag = 'Y'
    else
      project_setting.mm_flag = 'N'
    end
    if params[:sw_flag]
      project_setting.sw_flag = 'Y'
    else
      project_setting.sw_flag = 'N'
    end
    if params[:bn_flag]
      project_setting.bn_flag = 'Y'
    else
      project_setting.bn_flag = 'N'
    end
    if params[:hm_flag]
      project_setting.hm_flag = 'Y'
    else
      project_setting.hm_flag = 'N'
    end
    if params[:caar_diagram]
      project_setting.caar_diagram = 'Y'
    else
      project_setting.caar_diagram = 'N'
    end
    if params[:caar_t]
      project_setting.caar_t = 'Y'
    else
      project_setting.caar_t = 'N'
    end
    if params[:aar_diagram]
      project_setting.aar_diagram = 'Y'
    else
      project_setting.aar_diagram = 'N'
    end
    if params[:aar_t]
      project_setting.aar_t = 'Y'
    else
      project_setting.aar_t = 'N'
    end
    if params[:sign_test]
      project_setting.sign_test = 'Y'
    else
      project_setting.sign_test = 'N'
    end
    if params[:rank_test]
      project_setting.rank_test = 'Y'
    else
      project_setting.rank_test = 'N'
    end
    if params[:sd_ar_test]
      project_setting.sd_ar_test = 'Y'
    else
      project_setting.sd_ar_test = 'N'
    end
    if params[:sd_cr_test]
      project_setting.sd_cr_test = 'Y'
    else
      project_setting.sd_cr_test = 'N'
    end
    begin
      if !params[:tax_rate].empty?
        project_setting.tax_rate = params[:tax_rate]
      end
    rescue
    end
    project_setting.save

    if "#{params[:leadlag_size]}"!="#{project_setting.leadlag_size}"
      begin
        project_setting.leadlag_size = params[:leadlag_size].to_i
        project_setting.save
      rescue
      end
      min_est = "#{project_setting.min_est}"
      max_est = "#{project_setting.max_est}"
      min_event = "#{project_setting.min_event}"
      max_event = "#{project_setting.max_event}"
      leadlag_size = params[:leadlag_size]
      min_event = "#{project_setting.min_event-leadlag_size.to_i}"
      max_event = "#{project_setting.max_event+leadlag_size.to_i}"

      market_type = "S"
      market_id = 1

      as_market = RunningStock.find(:first, :conditions=>["project_setting_id=? AND rm_flag=?", project_setting.id,'Y'])
      if as_market
        market_type = as_market.stock_type
        if as_market.stock_type=='S'
          market_id = as_market.stock_id
        else
          market_id = as_market.user.stock_id
        end
      end
      running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND rm_flag!=?", project_setting.id,'Y'])
      running_stocks.each do |rs|
        update_running_stock(rs, min_est.to_i, max_est.to_i, min_event.to_i, max_event.to_i)
        fill_market_window_date(rs.id, market_id, market_type, min_est, max_est, min_event, max_event)
      end
    end
    redirect_to :action=>"model_page", :word=>"Saved : #{Time.now}"
  end

  def result_page
    @word = nil
    if params[:word]
      @word = params[:word]
    end
    @tab = "result"
    @project = Project.find(session[:selected_project_id])
    @project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", session[:selected_project_id]])
    @running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND rm_flag!=? AND min_est_pass=? AND max_est_pass=? AND min_event_pass=? AND max_event_pass=?",@project_setting.id,'Y','Y','Y','Y','Y'], :order=>"id")
    @filter_stock_count = RunningStock.count(:all, :conditions=>["project_setting_id=? AND rm_flag!=? AND running=? AND min_est_pass=? AND max_est_pass=? AND min_event_pass=? AND max_event_pass=?",@project_setting.id,'Y','Y','Y','Y','Y','Y'])
    @market_stock_type = "System's"
    @market_stock = Stock.find(1)
    defined_market = RunningStock.find(:first, :conditions=>["project_setting_id=? AND rm_flag=?",@project_setting.id,'Y'], :order=>"id desc")
    if defined_market
      if defined_market.stock_type=='S'
        mk = Stock.find(:first, :conditions=>["id=?",defined_market.stock_id])
        if mk
          @market_stock = mk
        end
      else
        mk = UserStock.find(:first, :conditions=>["id=?",defined_market.user_stock_id])
        if mk
          @market_stock = mk
          @market_stock_type = "Yours"
        end        
      end
    end
    @results = RunningResult.paginate(:all, :page=>params[:page], :per_page=>5, :conditions=>["project_setting_id=?",@project_setting.id], :order=>"id desc")
    @all_projects = all_active_project_array
    render :action=>"result_page", :layout=>"blank_layout"
  end

  def result_page_save
    project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", session[:selected_project_id]])

    if params[:mm_flag]
      project_setting.mm_flag = 'Y'
    else
      project_setting.mm_flag = 'N'
    end
    if params[:sw_flag]
      project_setting.sw_flag = 'Y'
    else
      project_setting.sw_flag = 'N'
    end
    if params[:bn_flag]
      project_setting.bn_flag = 'Y'
    else
      project_setting.bn_flag = 'N'
    end
    if params[:hm_flag]
      project_setting.hm_flag = 'Y'
    else
      project_setting.hm_flag = 'N'
    end
    if params[:caar_diagram]
      project_setting.caar_diagram = 'Y'
    else
      project_setting.caar_diagram = 'N'
    end
    if params[:caar_t]
      project_setting.caar_t = 'Y'
    else
      project_setting.caar_t = 'N'
    end
    if params[:aar_diagram]
      project_setting.aar_diagram = 'Y'
    else
      project_setting.aar_diagram = 'N'
    end
    if params[:aar_t]
      project_setting.aar_t = 'Y'
    else
      project_setting.aar_t = 'N'
    end
    if params[:sign_test]
      project_setting.sign_test = 'Y'
    else
      project_setting.sign_test = 'N'
    end
    if params[:rank_test]
      project_setting.rank_test = 'Y'
    else
      project_setting.rank_test = 'N'
    end
    if params[:sd_ar_test]
      project_setting.sd_ar_test = 'Y'
    else
      project_setting.sd_ar_test = 'N'
    end
    if params[:sd_cr_test]
      project_setting.sd_cr_test = 'Y'
    else
      project_setting.sd_cr_test = 'N'
    end
    if params[:ar]
      project_setting.ar = 'Y'
    else
      project_setting.ar = 'N'
    end
    if params[:car]
      project_setting.car = 'Y'
    else
      project_setting.car = 'N'
    end
    begin
      if !params[:tax_rate].empty?
        project_setting.tax_rate = params[:tax_rate]
      end
    rescue
    end
    project_setting.save

    running_array = Array.new
    running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND rm_flag!=?", project_setting.id,'Y'])
    running_stocks.each do |rs|
      if params["running_#{rs.id}"]
        running_array = running_array << "#{rs.id}"
        rs.running = 'Y'
      else
        rs.running = 'N'
      end
      rs.save
    end

    if params[:save_group]
      urss = UserRunningStock.find(:all, :conditions=>["project_id=?", session[:selected_project_id]])
      urss.each do |ur|
        ur.use_flag = 'N'
        ur.save
      end
      urs = UserRunningStock.find(:first, :conditions=>["name=? AND project_id=?", "#{params[:group_name]}", session[:selected_project_id]])
      if !urs
        urs = UserRunningStock.new
        urs.project_id = session[:selected_project_id]
        urs.user_id = session[:user].id
        urs.name = params[:group_name]
      end
      urs.running_list = running_array.join(',')
      urs.use_flag = 'Y'
      urs.save
    end

    if params[:update_group]
      if params[:selected_group_id]!="0"
        urss = UserRunningStock.find(:all, :conditions=>["project_id=?", session[:selected_project_id]])
        urss.each do |ur|
          ur.use_flag = 'N'
          ur.save
        end
        urs = UserRunningStock.find(params[:selected_group_id])
        urs.running_list = running_array.join(',')
        urs.use_flag = 'Y'
        urs.save
      end
    end

    if params[:save_setting]
      if params[:selected_group_id]!="0"
        urss = UserRunningStock.find(:all, :conditions=>["project_id=?", session[:selected_project_id]])
        urss.each do |ur|
          ur.use_flag = 'N'
          ur.save
        end
        urs = UserRunningStock.find(params[:selected_group_id])
        urs.running_list = running_array.join(',')
        urs.use_flag = 'Y'
        urs.save
      else
        urss = UserRunningStock.find(:all, :conditions=>["project_id=?", session[:selected_project_id]])
        urss.each do |ur|
          ur.use_flag = 'N'
          ur.save
        end
      end
    end

    if params[:select_group]
      if params[:selected_group_id]!="0"
        urss = UserRunningStock.find(:all, :conditions=>["project_id=?", session[:selected_project_id]])
        urss.each do |ur|
          ur.use_flag = 'N'
          ur.save
        end
        urs = UserRunningStock.find(params[:selected_group_id])
        urs.use_flag = 'Y'
        urs.save
        running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND rm_flag!=?", project_setting.id,'Y'])
        running_stocks.each do |rs|
          if urs.running_list.split(',').include? "#{rs.id}"
            rs.running = 'Y'
          else
            rs.running = 'N'
          end
          rs.save
        end
      else
        urss = UserRunningStock.find(:all, :conditions=>["project_id=?", session[:selected_project_id]])
        urss.each do |ur|
          ur.use_flag = 'N'
          ur.save
        end
        running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND rm_flag!=? AND running=?", project_setting.id,'Y','N'])
        running_stocks.each do |rs|
          rs.running = 'Y'
          rs.save
        end
      end
    end

    if params[:delete_group]
      if params[:selected_group_id]!="0"
        urs = UserRunningStock.find(params[:selected_group_id])
        urs.destroy
        urss = UserRunningStock.find(:all, :conditions=>["project_id=?", session[:selected_project_id]])
        urss.each do |ur|
          ur.use_flag = 'N'
          ur.save
        end
        running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND rm_flag!=? AND running=?", project_setting.id,'Y','N'])
        running_stocks.each do |rs|
          rs.running = 'Y'
          rs.save
        end
      end
    end

    if "#{params[:leadlag_size]}"!="#{project_setting.leadlag_size}"
      begin
        project_setting.leadlag_size = params[:leadlag_size].to_i
        project_setting.save
      rescue
      end
      min_est = "#{project_setting.min_est}"
      max_est = "#{project_setting.max_est}"
      min_event = "#{project_setting.min_event}"
      max_event = "#{project_setting.max_event}"
      leadlag_size = params[:leadlag_size]
      min_event = "#{project_setting.min_event-leadlag_size.to_i}"
      max_event = "#{project_setting.max_event+leadlag_size.to_i}"

      market_type = "S"
      market_id = 1

      as_market = RunningStock.find(:first, :conditions=>["project_setting_id=? AND rm_flag=?", project_setting.id,'Y'])
      if as_market
        market_type = as_market.stock_type
        if as_market.stock_type=='S'
          market_id = as_market.stock_id
        else
          market_id = as_market.user.stock_id
        end
      end
      running_stocks.each do |rs|
        update_running_stock(rs, min_est.to_i, max_est.to_i, min_event.to_i, max_event.to_i)
        fill_market_window_date(rs.id, market_id, market_type, min_est, max_est, min_event, max_event)
      end
    end
    redirect_to :action=>"result_page", :word=>"Saved : #{Time.now}"
  end

  def result_page_save_bk
    @project = Project.find(session[:selected_project_id])
    @project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", session[:selected_project_id]])
    @running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND rm_flag!=? AND min_est_pass=? AND max_est_pass=? AND min_event_pass=? AND max_event_pass=?",@project_setting.id,'Y','Y','Y','Y','Y'], :order=>"id")
    @market_stock_type = "System's"
    @market_stock = Stock.find(1)
    defined_market = RunningStock.find(:first, :conditions=>["project_setting_id=? AND rm_flag=?",@project_setting.id,'Y'], :order=>"id desc")
    if defined_market
      if defined_market.stock_type=='S'
        mk = Stock.find(:first, :conditions=>["id=?",defined_market.stock_id])
        if mk
          @market_stock = mk
        end
      else
        mk = UserStock.find(:first, :conditions=>["id=?",defined_market.user_stock_id])
        if mk
          @market_stock = mk
          @market_stock_type = "Yours"
        end
      end
    end
    rr = RunningResult.new
    rr.project_id = session[:selected_project_id]
    rr.project_setting_id = @project_setting.id
    rr.user_id = session[:user_id]
    rr.total_data = @running_stocks.size
#    begin
      rr.text_result = get_running_result(@project_setting, @running_stocks, @market_stock.id, @market_stock_type)
#    rescue
#    end
    rr.remark = params[:remark]
    rr.save
    redirect_to :action=>"result_page", :word=>"Finished : #{Time.now}"
  end

  def result_page_save2
    project = Project.find(session[:selected_project_id])
    project_setting = ProjectSetting.find(:first, :conditions=>["project_id=?", session[:selected_project_id]])
    running_stocks = RunningStock.find(:all, :conditions=>["project_setting_id=? AND running=? AND rm_flag!=? AND min_est_pass=? AND max_est_pass=? AND min_event_pass=? AND max_event_pass=?",project_setting.id,'Y','Y','Y','Y','Y','Y'], :order=>"id")
    market_stock_type = "System's"
    market_stock = Stock.find(1)
    defined_market = RunningStock.find(:first, :conditions=>["project_setting_id=? AND rm_flag=?",project_setting.id,'Y'], :order=>"id desc")
    if defined_market
      if defined_market.stock_type=='S'
        mk = Stock.find(:first, :conditions=>["id=?",defined_market.stock_id])
        if mk
          market_stock = mk
        end
      else
        mk = UserStock.find(:first, :conditions=>["id=?",defined_market.user_stock_id])
        if mk
          market_stock = mk
          market_stock_type = "Yours"
        end
      end
    end
    rr = RunningResult.new
    rr.project_id = session[:selected_project_id]
    rr.project_setting_id = project_setting.id
    rr.user_id = session[:user_id]
    rr.total_data = running_stocks.size
#    begin
      rr.text_result = get_running_result(project_setting, running_stocks, market_stock.id, market_stock_type, params[:remark])
#    rescue
#    end
    rr.remark = params[:remark]
    rr.save
    @word = "Finished : #{Time.now}"
    @results = RunningResult.paginate(:all, :page=>params[:page], :per_page=>5, :conditions=>["project_setting_id=?",project_setting.id], :order=>"id desc")
    render :action=>"result_page_save2", :layout=>false
  end

  def view_result
    @result = RunningResult.find(params[:id])
    render :action=>"view_result", :layout=>"blank_all"
  end

  def result_delete
    result = RunningResult.find(params[:id])
    if result
      result.destroy
    end
    redirect_to :action=>"result_page", :word=>"Deleted: #{Time.now}"
  end

  def pickstock
    render :text=>params[:stock_1]
  end

  def add_data
    @no = params[:no]
    render :action=>"add_data", :layout=>false
  end

  def add_userdata
    @no = params[:no]
    render :action=>"add_userdata", :layout=>false
  end

  def show_validate_chart
    err = 0
    begin
      @event_date = Date.parse(params[:ed])
    rescue
      err = 1
    end
    if err==0
      @id = params[:id]
      @stock_type = params[:stock_type]
      @event_date = Date.parse(params[:ed])
      @min_est = params[:min_est]
      @max_est = params[:max_est]
      @min_event = "#{params[:min_event].to_i-params[:leadlag_size].to_i}"
      @max_event = "#{params[:max_event].to_i+params[:leadlag_size].to_i}"
      @leadlag_size = params[:leadlag_size]
      @no = params[:no]
      render :action=>"show_validate_chart", :layout=>false
    else
      render :text=>"Invalid Date", :layout=>false
    end
  end

  def show_validate_chart2
    err = 0
    begin
      @event_date = Date.parse(params[:ed])
    rescue
      err = 1
    end
    if err==0
      @id = params[:id]
      @stock_type = params[:stock_type]
      @event_date = Date.parse(params[:ed])
      @min_est = params[:min_est]
      @max_est = params[:max_est]
      @min_event = "#{params[:min_event].to_i-params[:leadlag_size].to_i}"
      @max_event = "#{params[:max_event].to_i+params[:leadlag_size].to_i}"
      @no = params[:no]
      render :action=>"show_validate_chart2", :layout=>false
    else
      render :text=>"Invalid Date", :layout=>false
    end
  end

  def selected_system_stock
    @no = params[:no]
    @id = params[:id]
    @stock = Stock.find(:first, :conditions=>["id=?", params[:id]])
    #render :text=>@no, :layout=>false
    render :action=>"selected_system_stock", :layout=>false
  end

  def selected_user_stock
    @no = params[:no]
    @id = params[:id]
    @stock = UserStock.find(:first, :conditions=>["id=?", params[:id]])
    #render :text=>@no, :layout=>false
    render :action=>"selected_user_stock", :layout=>false
  end

  def price_return_chart
    @id_type = "#{params[:id]}|#{params[:stock_type]}"
    render :action=>"price_return_chart", :layout=>"blank_zoomchart_layout"
  end

  def return_chart_xml
    para = params[:id].split('|')
    stock_id = para[0]
    stock_type = para[1]
    if stock_type=='S'
      stock = Stock.find(:first, :conditions=>["id=?",stock_id])
      xml = "<chart decimals='2' compactDataMode='1' dataSeparator='|' palette='3' caption='#{stock.s_symbol}' subCaption='' connectNullData='0' formatNumber='1' formatNumberScale='1'>"
      xml += "<categories>"
      trades = StockTrade.find(:all, :conditions=>["stock_id=?", stock_id], :order=>"trade_date")
      date_array = trades.map{|t| "#{t.trade_date}"}
      xml += date_array.join('|')
      xml += "</categories>"
      xml += "<dataset seriesName='Daily Return (%)'>"
      value_array = trades.map{|t| begin "#{t.daily_return * 100.0}" rescue "#{t.daily_return}" end}
      xml += value_array.join('|')
      xml += "</dataset>"
      xml += "</chart>"
    else
      stock = UserStock.find(:first, :conditions=>["id=?",stock_id])
      xml = "<chart decimals='2' compactDataMode='1' dataSeparator='|' palette='3' caption='#{stock.s_symbol}' subCaption='' connectNullData='0' formatNumber='1' formatNumberScale='1'>"
      xml += "<categories>"
      trades = UserStockTrade.find(:all, :conditions=>["user_stock_id=?", stock_id], :order=>"trade_date")
      date_array = trades.map{|t| "#{t.trade_date}"}
      xml += date_array.join('|')
      xml += "</categories>"
      xml += "<dataset seriesName='Daily Return (%)'>"
      value_array = trades.map{|t| begin "#{t.daily_return * 100.0}" rescue "#{t.daily_return}" end}
      xml += value_array.join('|')
      xml += "</dataset>"
      xml += "</chart>"
    end
    headers["Content-Type"] = "text/xml"
    render :text=>xml
  end

  def price_chart_xml
    para = params[:id].split('|')
    stock_id = para[0]
    stock_type = para[1]
    if stock_type=='S'
      stock = Stock.find(:first, :conditions=>["id=?",stock_id])
      xml = "<chart decimals='2' compactDataMode='1' dataSeparator='|' palette='3' caption='#{stock.s_symbol}' subCaption='' connectNullData='0' formatNumber='1' formatNumberScale='1'>"
      xml += "<categories>"
      trades = StockTrade.find(:all, :conditions=>["stock_id=?", stock_id], :order=>"trade_date")
      date_array = trades.map{|t| "#{t.trade_date}"}
      xml += date_array.join('|')
      xml += "</categories>"
      xml += "<dataset seriesName='Price'>"
      value_array = trades.map{|t| "#{t.price}"}
      xml += value_array.join('|')
      xml += "</dataset>"
      xml += "</chart>"
    else
      stock = UserStock.find(:first, :conditions=>["id=?",stock_id])
      xml = "<chart decimals='2' compactDataMode='1' dataSeparator='|' palette='3' caption='#{stock.s_symbol}' subCaption='' connectNullData='0' formatNumber='1' formatNumberScale='1'>"
      xml += "<categories>"
      trades = UserStockTrade.find(:all, :conditions=>["user_stock_id=?", stock_id], :order=>"trade_date")
      date_array = trades.map{|t| "#{t.trade_date}"}
      xml += date_array.join('|')
      xml += "</categories>"
      xml += "<dataset seriesName='Price'>"
      value_array = trades.map{|t| "#{t.price}"}
      xml += value_array.join('|')
      xml += "</dataset>"
      xml += "</chart>"
    end
    headers["Content-Type"] = "text/xml"
    render :text=>xml
  end

  def check_est_event_pass(id, stock_type, event_date, min_est, max_est, min_event, max_event)
    pass = ['N','N','N','N']
    date = [nil,nil,nil,nil]
    min_est_date = nil
    max_est_date = nil
    min_event_date = nil
    max_event_date = nil
    if stock_type=='S'
      st = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date<=?",id,event_date], :order=>"trade_date desc")
      
      min_est_date = st[min_est.to_i * -1]
      max_est_date = st[max_est.to_i * -1]
      min_event_date = st[min_event.to_i * -1]
      st = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=?",id,event_date], :order=>"trade_date")

      max_event_date = st[max_event.to_i]
    else
      st = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date<=?",id,event_date], :order=>"trade_date desc")

      min_est_date = st[min_est.to_i * -1]
      max_est_date = st[max_est.to_i * -1]
      min_event_date = st[min_event.to_i * -1]
      st = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=?",id,event_date], :order=>"trade_date")

      max_event_date = st[max_event.to_i]
    end

    if min_est_date
      if min_est_date.daily_return
        pass[0] = 'Y'
        date[0] = min_est_date.trade_date
      end
    end
    if max_est_date
      if max_est_date.daily_return
        pass[1] = 'Y'
        date[1] = max_est_date.trade_date
      end
    end
    if min_event_date
      if min_event_date.daily_return
        pass[2] = 'Y'
        date[2] = min_event_date.trade_date
      end
    end
    if max_event_date
      if max_event_date.daily_return
        pass[3] = 'Y'
        date[3] = max_event_date.trade_date
      end
    end
    return pass,date
  end

  def fill_market_window_date(id, market_id, market_type, min_est, max_est, min_event, max_event)
    min_est_date = nil
    max_est_date = nil
    min_event_date = nil
    max_event_date = nil
    rs = RunningStock.find(id)
    if market_type=='S'
      st = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date<=?",market_id,rs.event_date], :order=>"trade_date desc")
      min_est_date = st[min_est.to_i * -1]
      max_est_date = st[max_est.to_i * -1]
      min_event_date = st[min_event.to_i * -1]
      st = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=?",market_id,rs.event_date], :order=>"trade_date")
      max_event_date = st[max_event.to_i]
    else
      st = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date<=?",market_id,rs.event_date], :order=>"trade_date desc")
      min_est_date = st[min_est.to_i * -1]
      max_est_date = st[max_est.to_i * -1]
      min_event_date = st[min_event.to_i * -1]
      st = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=?",market_id,rs.event_date], :order=>"trade_date")
      max_event_date = st[max_event.to_i]
    end
    if min_est_date
      if min_est_date.daily_return
        rs.market_min_est_date = min_est_date.trade_date
      end
    end
    if max_est_date
      if max_est_date.daily_return
        rs.market_max_est_date = max_est_date.trade_date
      end
    end
    if min_event_date
      if min_event_date.daily_return
        rs.market_min_event_date = min_event_date.trade_date
      end
    end
    if max_event_date
      if max_event_date.daily_return
        rs.market_max_event_date = max_event_date.trade_date
      end
    end
    rs.save
  end

  def edit_remark
    @result = RunningResult.find(params[:id])
    render :action=>"edit_remark", :layout=>false
  end

  def save_edit_remark
    @result = RunningResult.find(params[:id])
    @result.remark = params[:remark]
    @result.save
    render :action=>"save_edit_remark", :layout=>false
  end

  def delete_flag_save
    p = Project.find(:first, :conditions=>["gencode=?", params[:id]])
    p.project_status = 'Deleted'
    p.save
    redirect_to :action=>"list"
  end

end
